package com.ocean.security.handler;

import com.ocean.cache.redis.IRedisCache;
import com.ocean.core.util.JwtUtil;
import com.ocean.core.util.constants.ConstantsCache;
import com.ocean.core.util.response.ResultSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权成功
 *
 * @author zhang
 * @since 2021/9/10
 */
@Component
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private IRedisCache iRedisCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        httpServletResponse.setStatus(200);
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String token = JwtUtil.generateJwtToken(principal.getUsername());
        iRedisCache.set(ConstantsCache.getInstance().getAuthenticationPrefix() + principal.getUsername(), principal, JwtUtil.EXPIRE);
        httpServletResponse.getWriter().print(ResultSet.ok(token));
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
